import React, { useEffect, useRef } from 'react';
import { Card, Table, Typography, Row, Col, Statistic } from 'antd';
import * as echarts from 'echarts';

const { Title, Text } = Typography;

// 模拟数据 - 用户城市等级分布
const mockData = [
  { city: '北京', level: 1, user_count: 8560, purchase_total: 125000, avg_purchase: 14.6 },
  { city: '上海', level: 1, user_count: 7890, purchase_total: 112000, avg_purchase: 14.2 },
  { city: '广州', level: 1, user_count: 5430, purchase_total: 81000, avg_purchase: 14.9 },
  { city: '深圳', level: 1, user_count: 6210, purchase_total: 95000, avg_purchase: 15.3 },
  { city: '杭州', level: 1.5, user_count: 4560, purchase_total: 65000, avg_purchase: 14.3 },
  { city: '南京', level: 1.5, user_count: 3890, purchase_total: 54000, avg_purchase: 13.9 },
  { city: '成都', level: 1.5, user_count: 5120, purchase_total: 72000, avg_purchase: 14.1 },
  { city: '武汉', level: 1.5, user_count: 4320, purchase_total: 61000, avg_purchase: 14.1 },
  { city: '西安', level: 2, user_count: 3450, purchase_total: 48000, avg_purchase: 13.9 },
  { city: '重庆', level: 2, user_count: 4650, purchase_total: 63000, avg_purchase: 13.6 },
  { city: '天津', level: 2, user_count: 3980, purchase_total: 55000, avg_purchase: 13.8 },
  { city: '苏州', level: 2, user_count: 4230, purchase_total: 58000, avg_purchase: 13.7 },
  { city: '厦门', level: 2.5, user_count: 2890, purchase_total: 40000, avg_purchase: 13.8 },
  { city: '青岛', level: 2.5, user_count: 3120, purchase_total: 43000, avg_purchase: 13.8 },
  { city: '大连', level: 2.5, user_count: 2780, purchase_total: 38000, avg_purchase: 13.7 },
  { city: '长沙', level: 2.5, user_count: 3450, purchase_total: 47000, avg_purchase: 13.6 },
  { city: '石家庄', level: 3, user_count: 2670, purchase_total: 36000, avg_purchase: 13.5 },
  { city: '郑州', level: 3, user_count: 3560, purchase_total: 48000, avg_purchase: 13.5 },
  { city: '合肥', level: 3, user_count: 2980, purchase_total: 40000, avg_purchase: 13.4 },
  { city: '福州', level: 3, user_count: 2890, purchase_total: 39000, avg_purchase: 13.5 },
];

// 城市等级标签映射
const levelLabels = {
  1: '一线',
  1.5: '新一线',
  2: '二线',
  2.5: '三线',
  3: '四线及以下'
};

// 定义表格列
const columns = [
  {
    title: '城市',
    dataIndex: 'city',
    key: 'city',
  },
  {
    title: '城市等级',
    dataIndex: 'level',
    key: 'level',
    render: (level) => levelLabels[level] || level,
  },
  {
    title: '用户数量',
    dataIndex: 'user_count',
    key: 'user_count',
  },
  {
    title: '总消费金额',
    dataIndex: 'purchase_total',
    key: 'purchase_total',
    render: (text) => `¥${text.toLocaleString()}`,
  },
  {
    title: '人均消费',
    dataIndex: 'avg_purchase',
    key: 'avg_purchase',
    render: (text) => `¥${text.toFixed(2)}`,
  },
];

const UserCityLevel = () => {
  const barChartRef = useRef(null);
  const pieChartRef = useRef(null);
  const barChartInstance = useRef(null);
  const pieChartInstance = useRef(null);

  useEffect(() => {
    // 初始化柱状图
    if (barChartRef.current && !barChartInstance.current) {
      barChartInstance.current = echarts.init(barChartRef.current);
    }

    // 初始化饼图
    if (pieChartRef.current && !pieChartInstance.current) {
      pieChartInstance.current = echarts.init(pieChartRef.current);
    }

    // 按城市等级分组统计
    const levelData = {};
    mockData.forEach(item => {
      if (!levelData[item.level]) {
        levelData[item.level] = {
          level: item.level,
          levelName: levelLabels[item.level],
          user_count: 0,
          purchase_total: 0
        };
      }
      levelData[item.level].user_count += item.user_count;
      levelData[item.level].purchase_total += item.purchase_total;
    });

    const levelStats = Object.values(levelData).sort((a, b) => a.level - b.level);
    
    // 准备柱状图数据
    const barData = [...mockData].sort((a, b) => b.user_count - a.user_count).slice(0, 10);
    const cities = barData.map(item => item.city);
    const userCounts = barData.map(item => item.user_count);
    const avgPurchases = barData.map(item => item.avg_purchase);

    // 准备饼图数据
    const pieData = levelStats.map(item => ({
      name: item.levelName,
      value: item.user_count
    }));

    // 柱状图配置
    const barOption = {
      title: {
        text: '用户量最多的城市Top10',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params) {
          const dataIndex = params[0].dataIndex;
          const cityData = barData[dataIndex];
          return `城市: ${cityData.city}<br/>` +
                 `城市等级: ${levelLabels[cityData.level]}<br/>` +
                 `用户数量: ${cityData.user_count}<br/>` +
                 `人均消费: ¥${cityData.avg_purchase.toFixed(2)}`;
        }
      },
      legend: {
        data: ['用户数量', '人均消费'],
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: cities,
        axisLabel: {
          interval: 0,
          rotate: 45
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '用户数量',
          position: 'left',
        },
        {
          type: 'value',
          name: '人均消费(¥)',
          position: 'right',
        }
      ],
      series: [
        {
          name: '用户数量',
          type: 'bar',
          data: userCounts,
          itemStyle: {
            color: '#5470c6'
          }
        },
        {
          name: '人均消费',
          type: 'line',
          yAxisIndex: 1,
          data: avgPurchases,
          itemStyle: {
            color: '#91cc75'
          }
        }
      ]
    };

    // 饼图配置
    const pieOption = {
      title: {
        text: '城市等级用户分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: levelStats.map(item => item.levelName)
      },
      series: [
        {
          name: '用户数量',
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    // 渲染图表
    if (barChartInstance.current) {
      barChartInstance.current.setOption(barOption);
    }
    if (pieChartInstance.current) {
      pieChartInstance.current.setOption(pieOption);
    }

    // 响应式调整
    const handleResize = () => {
      if (barChartInstance.current) {
        barChartInstance.current.resize();
      }
      if (pieChartInstance.current) {
        pieChartInstance.current.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (barChartInstance.current) {
        barChartInstance.current.dispose();
        barChartInstance.current = null;
      }
      if (pieChartInstance.current) {
        pieChartInstance.current.dispose();
        pieChartInstance.current = null;
      }
    };
  }, []);

  // 计算统计信息
  const totalUsers = mockData.reduce((sum, item) => sum + item.user_count, 0);
  const totalPurchase = mockData.reduce((sum, item) => sum + item.purchase_total, 0);
  const overallAvgPurchase = totalPurchase / totalUsers;
  const maxUserCity = mockData.reduce((prev, current) => 
    prev.user_count > current.user_count ? prev : current
  );
  const maxPurchaseCity = mockData.reduce((prev, current) => 
    prev.purchase_total > current.purchase_total ? prev : current
  );

  return (
    <div>
      <Title level={4}>用户城市等级分析</Title>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={8}>
          <Card>
            <Title level={5}>统计概览</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic 
                  title="总用户数" 
                  value={totalUsers}
                  precision={0}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="总消费额" 
                  value={totalPurchase}
                  precision={0}
                  prefix="¥"
                  valueStyle={{ color: '#cf1322' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="平均消费" 
                  value={overallAvgPurchase}
                  precision={2}
                  prefix="¥"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="数据覆盖城市" 
                  value={mockData.length}
                  precision={0}
                  suffix="个"
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
            <div style={{ marginTop: 20 }}>
              <div style={{ marginBottom: 10 }}>
                <Text strong>用户量最多城市: </Text>
                {maxUserCity.city} ({maxUserCity.user_count}人)
              </div>
              <div>
                <Text strong>消费额最高城市: </Text>
                {maxPurchaseCity.city} (¥{maxPurchaseCity.purchase_total.toLocaleString()})
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={16}>
          <Card>
            <div ref={pieChartRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col span={24}>
          <Card>
            <div ref={barChartRef} style={{ width: '100%', height: 400 }} />
          </Card>
        </Col>
      </Row>
      <Card style={{ marginTop: 20 }}>
        <Title level={5}>详细数据列表</Title>
        <Table columns={columns} dataSource={mockData} rowKey="city" pagination={{ pageSize: 10 }} />
      </Card>
    </div>
  );
};

export default UserCityLevel;